package com.maezia.tdr.common;

import com.maezia.tdr.service.RedisMessageService;
import com.maezia.tdr.common.enums.RedisMessageEnum;
import com.maezia.tdr.common.redis.BaseRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class RedisMessageListener extends BaseRedisRepository<String> implements MessageListener {

    private ExecutorService threadPool = Executors.newScheduledThreadPool(10);

    @Autowired
    private Map<String, RedisMessageService> redisMessageService;

    public RedisMessageListener() {
        super(String.class);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(pattern);
        if (!ObjectUtils.isEmpty(message.getBody())) {
            threadPool.submit(() -> {
                try {
                    RedisMessageEnum messageEnum = RedisMessageEnum.getRedisMessageEnum(topic);
                    String messageBody = new String(message.getBody());
                    switch (messageEnum) {
                        case REPORT_POCESSING_SERVICE:
                            RedisMessageService reportPocessingService = redisMessageService.get(messageEnum.getName());
                            reportPocessingService.pocessing(messageBody);
                            break;
                        case LOGGING_POCESSING_SERVICE:
                            RedisMessageService loggingPocessingService = redisMessageService.get(messageEnum.getName());
                            loggingPocessingService.pocessing(messageBody);
                            break;
                    }
                } catch (Exception e) {
                    log.error("Exception:", e);
                }
            });
        }
    }
}
